let mysql = require('mysql');

const pool = mysql.createPool({
    host     :  '127.0.0.1',
    user     :  'root',
    password :  'Djy319677',
    database :  'test'
  })
class Mysql_student {
    constructor(){

    }

    // async dbop( sql, values ) {
    //     // 返回一个 Promise
    //     return new Promise(( resolve, reject ) => {
    //       pool.getConnection(function(err, connection) {
    //         if (err) {
    //           reject( err )
    //         } else {
    //           connection.query(sql, values, ( err, rows) => {
      
    //             if ( err ) {
    //               reject( err )
    //             } else {
    //               resolve( rows )
    //             }
    //             // 结束会话
    //             connection.release()
    //           })
    //         }
    //       })
    //     })
    //   }
    async dbop (sql) {
        return await this.dbOp(sql);
    }


    async dbOp(sql, sqlParam) {
        var connection = null;
        
            connection = mysql.createConnection({
                host     :  '127.0.0.1',
                user     :  'root',
                password :  'Djy319677',
                database :  'test'
              })
        
        
        return await this.dbOp1(sql, sqlParam, connection);
    }

    async dbOp1(sql, sqlParam, connection) { 
        var promise = new Promise((resolve, reject) => {
            connection.query(sql, sqlParam, (err, result) => {
                if (err) {
                    console.error('[dbOp1 error] - ' + err.message);
                    //connection.destroy();
                    reject(err);
                } else {
                    //connection.destroy();
                    resolve(result);
                }

                
                    //connection.end();
                    connection.destroy();
                
            });
        });

        return promise;
    }
}

module.exports = Mysql_student;